package com.ocom.payhandle.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ocom.common.HttpUtils;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.card.*;
import com.ocom.common.entity.pay.EntityXfRecordProcessExtend;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.mealorder.RefundOrderDishesRequest;
import com.ocom.common.request.payhandle.FeeRefundRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.payhandle.feign.XfRecordFeign;
import com.ocom.payhandle.fun.PayHandleFunService;
import com.ocom.payhandle.mq.business.saveorder.SaveOrderProductService;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.MqSaveOrderVo;
import com.ocom.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;


@Slf4j
@RestController
public class ParaRefundController {

    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    PayHandleFunService payHandleFunService;

    @Autowired
    private XfCardInfoService xfCardInfoService;

    @Autowired
    private XfAccountInfoService xfAccountInfoService;

    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;

    @Autowired
    private XfRecordFeign xfRecordFeign;

    @Resource
    private RedisUtil redisUtil;

//    @Value("${pay.url}")
//    private String payUrl;
    @Autowired
    private SaveOrderProductService saveOrderProductService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private XfRecordProcessExxxService xfRecordProcessExxxService;

    @Autowired
    private XfRecordProcessExtendService xfRecordProcessExtendService;

    @PostMapping(PayHandleUrl.URL_PayHandle_paraRefund)
    public Result paraRefund(@Valid @RequestBody FeeRefundRequest request){
        try {
            //查询订单号是否存在
            EntityXfRecordProcessExxx entityXfRecordProcess =xfRecordProcessExxxService.selectTradeNo(request.getCompanyId(),request.getOrigTradeNo(),null);
            if (entityXfRecordProcess ==null){
                //原订单号不存在
                return ResultUtil.error(ResultEnum.Err_3036);
            }
            Integer consState = entityXfRecordProcess.getConsState();
            request.setOrigTradeNo(entityXfRecordProcess.getOrderNo());
            if (entityXfRecordProcess.getIfRefund()>0){
                //
                return ResultUtil.error(ResultEnum.Err_3038);
            }
            Long totalAmount= entityXfRecordProcess.getRealMoney();
            Long id= entityXfRecordProcess.getId();
            Long ifRefund= entityXfRecordProcess.getIfRefund();
            String monthValue= entityXfRecordProcess.getMonthValue();

            String tradeNoRedis="refund:"+request.getCompanyId()+":"+request.getTradeNo();
            if (!redisUtil.lock(tradeNoRedis,60*60)){
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            if (entityXfRecordProcess.getPayState()!=1 ||
                    (entityXfRecordProcess.getConsState()!=1 && entityXfRecordProcess.getConsState()!=111 && entityXfRecordProcess.getConsState()!=3
            && entityXfRecordProcess.getConsState()!=5)){
                return ResultUtil.error(ResultEnum.Err_3037);
            }
            EntityXfRecordProcessExxx refundXfRecordProcess=xfRecordProcessExxxService.selectTradeNo(request.getCompanyId(),request.getTradeNo(),null);

            if (refundXfRecordProcess!=null){
                if (!refundXfRecordProcess.getOrigOrderNo().equals(request.getOrigTradeNo())){
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
                if (entityXfRecordProcess.getIfRefund()>0){
                    //退款成功
                    Map<String,Object> map=new HashMap<>();
                    map.put("refundAmount",request.getRefundAmount());
                    return ResultUtil.success(map);
                }
                if (refundXfRecordProcess.getPayState()==1){
                    Map<String,Object> map=new HashMap<>();
                    map.put("refundAmount",request.getRefundAmount());
                    return ResultUtil.success(map);
                }
            }


            entityXfRecordProcess.setId(null);
            Date date=new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setConsTime(date);
            if (Math.abs(entityXfRecordProcess.getRealMoney())<request.getRefundAmount()){
                //退款金额超过原订单支付金额
                return ResultUtil.error(ResultEnum.Err_3038);
            }
            entityXfRecordProcess.setConsMoney(-1 * entityXfRecordProcess.getConsMoney());
            entityXfRecordProcess.setDiscount(-1 * entityXfRecordProcess.getDiscount());
            entityXfRecordProcess.setRealMoney(-1 * entityXfRecordProcess.getRealMoney());
            entityXfRecordProcess.setChargeMoney(-1 * entityXfRecordProcess.getChargeMoney());
            entityXfRecordProcess.setConsState(6);
            entityXfRecordProcess.setOrigOrderNo(request.getOrigTradeNo());
            if(request.getTradeNo().startsWith("CART")){
                entityXfRecordProcess.setOrigOrderNo(entityXfRecordProcess.getPlatOrderNo());
            }
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setIfRefund(0l);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date,"yyyyMM"));
            entityXfRecordProcess.setPayAmount(-1 * entityXfRecordProcess.getPayAmount());
            try {
                int i=xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
                if (i<=0){
                    log.info("请求方式 p3vw3ida :【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】","付款码退款","feeRefund",request,ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
                if(entityXfRecordProcess.getReceiptPrice()!=null && entityXfRecordProcess.getReceiptPrice()!=0){
                    EntityXfRecordProcessExtend entityXfRecordProcessExtend =new EntityXfRecordProcessExtend();
                    entityXfRecordProcessExtend.setComId(request.getCompanyId());
                    entityXfRecordProcessExtend.setOrderNo(entityXfRecordProcess.getOrderNo());
                    entityXfRecordProcessExtend.setOrderId(entityXfRecordProcess.getId());
                    entityXfRecordProcessExtend.setCancelState(0);
                    entityXfRecordProcessExtend.setReceiptPrice(Math.abs(entityXfRecordProcess.getReceiptPrice()));
                    boolean j=xfRecordProcessExtendService.insertEntityXfRecordExtend(request.getCompanyId(), entityXfRecordProcessExtend);
                    if (!j){
                        log.info("请求方式 1ch00mf9 :【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】","付款码退款","feeRefund",request,ResultUtil.error(ResultEnum.Err_802));
                        //订单号重复
                        return ResultUtil.error(ResultEnum.Err_802);
                    }
                }
            }catch (Exception e){
                StackTraceElement ste =e.getStackTrace()[0];
                log.info("请求方式43:【{}】,机器号:【{}】,入库新增等待表的数据3:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund", entityXfRecordProcess,e,ste.getLineNumber());
                log.info("请求方式44:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】","付款码退款","feeRefund",request,ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }

            //修改等待表的原订单表的数据
            EntityXfRecordProcess updateXfRecordProcess=new EntityXfRecordProcess();
            updateXfRecordProcess.setId(id);
            updateXfRecordProcess.setRefundTime(new Date());
            updateXfRecordProcess.setIfRefund(ifRefund+1);

            //判断是走什么通道的
            //修改等待表的退款数据
            EntityXfRecordProcess updateXfRecordProces=new EntityXfRecordProcess();
            if (entityXfRecordProcess.getOpType()==2 || entityXfRecordProcess.getOpTypeDiff()>=200){
                //查询配置信息向统一平台发起支付
                EntiyXfMerchPayInfo entiyXfMerchPayInfo=payHandleFunService.configure(entityXfRecordProcess);

                if (entiyXfMerchPayInfo ==null){
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }
                Map<String,Object> retMap=new HashMap<>();
                retMap.put("company_id",entiyXfMerchPayInfo.getCompanyId());
                retMap.put("user_name",entiyXfMerchPayInfo.getUserName());
                retMap.put("password",entiyXfMerchPayInfo.getPassword());
                retMap.put("out_trade_no",request.getOrigTradeNo());
                if(request.getOrigTradeNo().startsWith("CART")){
                    retMap.put("out_trade_no",entityXfRecordProcess.getPlatOrderNo());
                }
                retMap.put("out_refund_no",request.getTradeNo());
                retMap.put("pos_no",null);
                retMap.put("total_amount", Math.abs(totalAmount));
                retMap.put("refund_fee", request.getRefundAmount());
                retMap.put("refund_desc", "退款");
                //向统一支付平台发起支付
                String json= "";
//				if(entiyEntiyXfRecordProcess.getPayWay()==28){
//					json= HttpUtils.postsJson(payUrl+"/withholding/refund.do",retMap);
//				}else{
                String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
                json= HttpUtils.postsJson(payUrl+"/unifiedmicropay/refund.do",retMap);
//				}
                JSONObject results= JSON.parseObject(json);
                if (results.getInteger("code")!=200){
                    log.info("请求方式45:【{}】,机器号:【{}】,入库新增的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecordProcess,"付款码退款失败");
                    log.info("请求方式46:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】","付款码退款","feeRefund",retMap,json);
                    return ResultUtil.error(ResultEnum.Err_3039);
                }
                Map<String,String> dataMap= (Map<String, String>) JSON.parse(results.getString("data"));
                updateXfRecordProces.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());

                entityXfRecordProcess.setChannelOrderNo(dataMap.get("refund_id"));
                entityXfRecordProcess.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));

                updateXfRecordProces.setChannelOrderNo(dataMap.get("refund_id"));
                updateXfRecordProces.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));
            }else if (//entiyEntiyXfRecordProcess.getOpType()==1 &&
                    entityXfRecordProcess.getOpTypeDiff()==100){
                //虚拟账户只允许退一次款，不然对于两个钱包都扣款的交易记录不好退款
                if(ifRefund>0){
                    return ResultUtil.error(ResultEnum.Err_3038);
                }
                if (StringUtils.isNotBlank(entityXfRecordProcess.getCardNo())) {
                    EntityCardInfo entityCardInfo=xfCardInfoService.selectCard(request.getCompanyId(), entityXfRecordProcess.getCardNo());
                    if (entityXfRecordProcess.getOpType()==22 || entityXfRecordProcess.getOpType()==21){
                        entityCardInfo=xfCardInfoService.selectCardByPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                    }

                    if(entityCardInfo!=null){
                        xfCardInfoService.upateCardMoneyA(request.getCompanyId(),entityCardInfo);
                    }
                }

//				EntityXfAccountInfo entityXfAccountInfo=xfAccountInfoService.selectAccount(request.getCompanyId(),entityCardInfo.getAccountNo());
                EntityXfAccountInfo entityXfAccountInfo=xfAccountInfoService.selectAccountPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                Long refundAmount= Long.valueOf(Math.abs(request.getRefundAmount()));
                Long chargeBalance=refundAmount+entityXfAccountInfo.getAccountRechargeMoney();
                //    Long subBalance= Long.valueOf(Math.abs(entityXfRecordProcess.getSubMoney()));
                entityXfRecordProcess.setChargeBalance(chargeBalance);
                entityXfRecordProcess.setPayTime(new Date());
                entityXfRecordProcess.setPayState(1);

                updateXfRecordProces.setId(entityXfRecordProcess.getId());
                updateXfRecordProces.setChargeBalance(chargeBalance);
                updateXfRecordProces.setPayTime(new Date());
                updateXfRecordProces.setPayState(1);

                try {
                    boolean bo = xfAccountInfoService.paraRefund(request.getCompanyId(),entityXfAccountInfo.getId(),id,entityXfRecordProcess,request.getRefundAmount());
                    if (!bo) {
                        return ResultUtil.error(ResultEnum.Err_3039);
                    }
                }catch (Exception e){
                    StackTraceElement ste =e.getStackTrace()[0];
                    log.info("请求方式148:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund",entityXfRecordProcess,e,ste.getLineNumber());
                    return ResultUtil.error(ResultEnum.Err_3039);
                }

                MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                mqSaveOrderVo.setComId(request.getCompanyId());
                mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

//                Result sveResult=xfRecordFeign.sveXfRecord(entityXfRecordProcess);
//                if (sveResult.getCode()!=200){
//                    log.info("请求方式50:【{}】,机器号:【{}】,入库成功的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecordProcess,"添加入库失败");
//                }

                //修改成功表的原订单表的数据
                updateXfRecordProcess.setComId(request.getCompanyId());
                updateXfRecordProcess.setOrderNo(request.getOrigTradeNo());
                updateXfRecordProcess.setMonthValue(monthValue);
//			updateXfRecordProcess.setDeviceNo(request.getMachNo());
                EntityXfRecord entityXfRecord=JSON.parseObject(JSON.toJSONString(updateXfRecordProcess),EntityXfRecord.class);
                Result result=xfRecordFeign.updateXfRecord(entityXfRecord);
                if (result.getCode()!=200){
                    log.info("请求方式49:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecord,"修改原订单信息失败");
                }

                Map<String,Object> map=new HashMap<>();
                map.put("refundAmount",request.getRefundAmount());
                return ResultUtil.success(map);
            }

            try {
                int i=xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(),updateXfRecordProcess);
                if (i<=0){
                    log.info("请求方式47:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】","付款码退款","feeRefund",updateXfRecordProcess,"付款码退款失败");
                }
            }catch (Exception e){
                StackTraceElement ste =e.getStackTrace()[0];
                log.info("请求方式48:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund",updateXfRecordProcess,e,ste.getLineNumber());
            }
            if(consState==3 || consState==5 ){
                xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrigOrderNo());
            }

            //修改成功表的原订单表的数据
            updateXfRecordProcess.setComId(request.getCompanyId());
            updateXfRecordProcess.setOrderNo(request.getOrigTradeNo());
            updateXfRecordProcess.setMonthValue(monthValue);
//			updateXfRecordProcess.setDeviceNo(request.getMachNo());
            EntityXfRecord entityXfRecord=JSON.parseObject(JSON.toJSONString(updateXfRecordProcess),EntityXfRecord.class);
            Result result=xfRecordFeign.updateXfRecord(entityXfRecord);
            if (result.getCode()!=200){
                log.info("请求方式49:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecord,"修改原订单信息失败");
            }
            if(consState==3 || consState==5 ){
                RefundOrderDishesRequest refundOrderDishesRequest =new RefundOrderDishesRequest();
                refundOrderDishesRequest.setComId(entityXfRecordProcess.getComId());
                refundOrderDishesRequest.setOrderNo(request.getOrigTradeNo());
                refundOrderDishesRequest.setMonthValue(entityXfRecordProcess.getMonthValue());
                refundOrderDishesRequest.setRemark("菜品退款");
                xfRecordFeign.refund(refundOrderDishesRequest);
            }

            //新增成功表的退款数据
            Date payTime=new Date();
            entityXfRecordProcess.setPayTime(payTime);
            entityXfRecordProcess.setPayState(1);


//            Result sveResult=xfRecordFeign.sveXfRecord(entityXfRecordProcess);
//            if (sveResult.getCode()!=200){
//                log.info("请求方式50:【{}】,机器号:【{}】,入库成功的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecordProcess,"添加入库失败");
//            }

            updateXfRecordProces.setId(entityXfRecordProcess.getId());
            updateXfRecordProces.setPayTime(payTime);
            updateXfRecordProces.setPayState(1);

            try {
                int i=xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(),updateXfRecordProces);
                if (i<=0){
                    log.info("请求方式51:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,返回:【{}】","付款码退款","feeRefund",updateXfRecordProcess,"等待表修改入库失败");
                }
            }catch (Exception e){
                StackTraceElement ste =e.getStackTrace()[0];
                log.info("请求方式52:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund",updateXfRecordProcess,e,ste.getLineNumber());
            }

            MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
            mqSaveOrderVo.setComId(request.getCompanyId());
            mqSaveOrderVo.setId(entityXfRecordProcess.getId());
            mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
            saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

            Map<String,Object> map=new HashMap<>();
            map.put("refundAmount",request.getRefundAmount());
            return ResultUtil.success(map);
        }catch (Exception e){
            StackTraceElement ste =e.getStackTrace()[0];
            log.info("请求方式53:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】","退款异常","feeRefund",request,e,ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

    @PostMapping(PayHandleUrl.URL_PayHandle_paraRefundB)
    public Result paraRefundB(@Valid @RequestBody FeeRefundRequest request){
        try {
            //查询订单号是否存在
            EntityXfRecordProcessExxx entityXfRecordProcess =xfRecordProcessExxxService.selectTradeNo(request.getCompanyId(),request.getOrigTradeNo(),null);
            if (entityXfRecordProcess ==null){
                //原订单号不存在
                return ResultUtil.error(ResultEnum.Err_3036);
            }
            //获取菜品的价格
            EntityXfGoodsListProcess entityXfGoodsListProcess = this.xfGoodsListProcessService.getXfGoodsList(request.getCompanyId(),request.getOrigTradeNo(),request.getFeeItemId());
            if(ObjectUtil.isEmpty(entityXfGoodsListProcess)){
                return ResultUtil.error(ResultEnum.Err_3080);
            }

            //已经退款的不可以重复退
//            if(entityXfGoodsListProcess.getIfRefund() >= 1){
//                return ResultUtil.error(ResultEnum.Err_3036);
//            }
            Integer consState = entityXfRecordProcess.getConsState();
            request.setOrigTradeNo(entityXfRecordProcess.getOrderNo());
            long countMoney = Math.abs(entityXfRecordProcess.getDiscount()) + Math.abs(entityXfRecordProcess.getConsMoney());

            List<EntityXfRecordProcessExxx> processList =  this.xfRecordProcessExxxService.selectRefundRecodes(request.getCompanyId(), request.getOrigTradeNo());
            AtomicLong refundMoney = new AtomicLong(0);
            AtomicLong refundDiscount = new AtomicLong(0);
            AtomicLong chargeMoney = new AtomicLong(0);
            AtomicLong payAmount = new AtomicLong(0);
            processList.forEach(entityXfRecordProcessExxx -> {
                refundMoney.set(refundMoney.get() + Math.abs(entityXfRecordProcessExxx.getDiscount()) + Math.abs(entityXfRecordProcessExxx.getConsMoney()));
                refundDiscount.set(refundDiscount.get() + Math.abs(entityXfRecordProcessExxx.getDiscount()));
                chargeMoney.set(chargeMoney.get() + Math.abs(entityXfRecordProcessExxx.getChargeMoney()));
                payAmount.set(payAmount.get() + Math.abs(entityXfRecordProcessExxx.getPayAmount()));
            });
//            return money.get();
            long a = countMoney - (refundMoney.get() + Math.abs(entityXfGoodsListProcess.getDishesPrice()));
            if( a < 0){
                return ResultUtil.error(ResultEnum.Err_3038);
            }


//            //获取已经退款的金额
//            if (entityXfRecordProcess.getIfRefund()>0){
//                //
//
//            }
            Long totalAmount= entityXfRecordProcess.getRealMoney();
            Long id= entityXfRecordProcess.getId();
            Long ifRefund= entityXfRecordProcess.getIfRefund();
            String monthValue= entityXfRecordProcess.getMonthValue();

            String tradeNoRedis="refund:"+request.getCompanyId()+":"+request.getTradeNo();
            if (!redisUtil.lock(tradeNoRedis,60*60)){
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }
            if (entityXfRecordProcess.getPayState()!=1 ||
                    (entityXfRecordProcess.getConsState()!=1 && entityXfRecordProcess.getConsState()!=111 && entityXfRecordProcess.getConsState()!=3
                            && entityXfRecordProcess.getConsState()!=5)){
                return ResultUtil.error(ResultEnum.Err_3037);
            }
            EntityXfRecordProcessExxx refundXfRecordProcess=xfRecordProcessExxxService.selectTradeNo(request.getCompanyId(),request.getTradeNo(),null);

            if (refundXfRecordProcess!=null){
//                if (!refundXfRecordProcess.getOrigOrderNo().equals(request.getOrigTradeNo())){
//                    //订单号重复
//                    return ResultUtil.error(ResultEnum.Err_802);
//                }
//                if (entityXfRecordProcess.getIfRefund()>0){
//                    //退款成功
//                    Map<String,Object> map=new HashMap<>();
//                    map.put("refundAmount",request.getRefundAmount());
//                    return ResultUtil.success(map);
//                }
                if (refundXfRecordProcess.getPayState()==1){
                    Map<String,Object> map=new HashMap<>();
                    map.put("refundAmount",request.getRefundAmount());
                    return ResultUtil.success(map);
                }
            }


            entityXfRecordProcess.setId(null);
            Date date=new Date();
            entityXfRecordProcess.setCreateTime(date);
            entityXfRecordProcess.setConsTime(date);
//            if (Math.abs(entityXfRecordProcess.getRealMoney())<request.getRefundAmount()){
//                //退款金额超过原订单支付金额
//                return ResultUtil.error(ResultEnum.Err_3038);
//            }
//          先退优惠、退完优惠 再退
            long canRefundDiscount = 0;
            long canConsMoney = 0;
            long canChargeMoney = 0;
            long canPayAmount = 0;
            if(Math.abs(entityXfRecordProcess.getDiscount()) - refundDiscount.get() > entityXfGoodsListProcess.getDishesPrice()){
                canRefundDiscount = entityXfGoodsListProcess.getDishesPrice(); //优惠金额 大于 菜品金额
            }else if((Math.abs(entityXfRecordProcess.getDiscount()) - refundDiscount.get() < entityXfGoodsListProcess.getDishesPrice()) && (Math.abs(entityXfRecordProcess.getDiscount()) - refundDiscount.get() > 0)){
                canRefundDiscount = Math.abs(entityXfRecordProcess.getDiscount()) - refundDiscount.get();
                canConsMoney = Math.abs(entityXfGoodsListProcess.getDishesPrice()) - canRefundDiscount;
            }else{
                canConsMoney = Math.abs(entityXfGoodsListProcess.getDishesPrice());
            }

            if(Math.abs(entityXfRecordProcess.getChargeMoney()) > 0){
                if(Math.abs(entityXfRecordProcess.getChargeMoney()) - chargeMoney.get() > Math.abs(canConsMoney) && canConsMoney > 0){
                    canChargeMoney = canConsMoney;
                } else if (Math.abs(entityXfRecordProcess.getChargeMoney()) - chargeMoney.get() < Math.abs(canConsMoney) && canConsMoney > 0) {
                    canChargeMoney = Math.abs(entityXfRecordProcess.getChargeMoney()) - chargeMoney.get();
                }
            }

            if(Math.abs(entityXfRecordProcess.getPayAmount()) > 0){
                if(Math.abs(entityXfRecordProcess.getPayAmount()) - payAmount.get() > Math.abs(canConsMoney) && canConsMoney > 0){
                    canPayAmount = canConsMoney;
                } else if (Math.abs(entityXfRecordProcess.getPayAmount()) - chargeMoney.get() < Math.abs(canConsMoney) && canConsMoney > 0) {
                    canPayAmount = Math.abs(entityXfRecordProcess.getPayAmount()) - payAmount.get();
                }
            }

            entityXfRecordProcess.setConsMoney(-1 * canConsMoney);
            entityXfRecordProcess.setDiscount(-1 * canRefundDiscount);
            entityXfRecordProcess.setRealMoney(-1 * entityXfGoodsListProcess.getDishesPrice().longValue());
            entityXfRecordProcess.setChargeMoney(-1 * canChargeMoney);
            entityXfRecordProcess.setConsState(6);
            entityXfRecordProcess.setOrigOrderNo(request.getOrigTradeNo());
            if(request.getTradeNo().startsWith("CART")){
                entityXfRecordProcess.setOrigOrderNo(entityXfRecordProcess.getPlatOrderNo());
            }
            entityXfRecordProcess.setPayState(0);
            entityXfRecordProcess.setOrderNo(request.getTradeNo());
            entityXfRecordProcess.setIfRefund(ifRefund + 1);
            entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date,"yyyyMM"));
            entityXfRecordProcess.setPayAmount(-1 * canPayAmount);
            try {
                int i=xfRecordProcessService.insertEntityXfRecord(request.getCompanyId(), entityXfRecordProcess);
                if (i<=0){
                    log.info("请求方式 p3vw3ida :【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】","付款码退款","feeRefund",request,ResultUtil.error(ResultEnum.Err_802));
                    //订单号重复
                    return ResultUtil.error(ResultEnum.Err_802);
                }
                if(entityXfRecordProcess.getReceiptPrice()!=null && entityXfRecordProcess.getReceiptPrice()!=0){
                    EntityXfRecordProcessExtend entityXfRecordProcessExtend =new EntityXfRecordProcessExtend();
                    entityXfRecordProcessExtend.setComId(request.getCompanyId());
                    entityXfRecordProcessExtend.setOrderNo(entityXfRecordProcess.getOrderNo());
                    entityXfRecordProcessExtend.setOrderId(entityXfRecordProcess.getId());
                    entityXfRecordProcessExtend.setCancelState(0);
                    entityXfRecordProcessExtend.setReceiptPrice(Math.abs(entityXfRecordProcess.getReceiptPrice()));
                    boolean j=xfRecordProcessExtendService.insertEntityXfRecordExtend(request.getCompanyId(), entityXfRecordProcessExtend);
                    if (!j){
                        log.info("请求方式 1ch00mf9 :【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】","付款码退款","feeRefund",request,ResultUtil.error(ResultEnum.Err_802));
                        //订单号重复
                        return ResultUtil.error(ResultEnum.Err_802);
                    }
                }
            }catch (Exception e){
                StackTraceElement ste =e.getStackTrace()[0];
                log.info("请求方式43:【{}】,机器号:【{}】,入库新增等待表的数据3:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund", entityXfRecordProcess,e,ste.getLineNumber());
                log.info("请求方式44:【{}】,机器号:【{}】,请求参数:【{}】,返回:【{}】","付款码退款","feeRefund",request,ResultUtil.error(ResultEnum.Err_802));
                //订单号重复
                return ResultUtil.error(ResultEnum.Err_802);
            }

            //修改等待表的原订单表的数据
            EntityXfRecordProcess updateXfRecordProcess=new EntityXfRecordProcess();
            updateXfRecordProcess.setId(id);
            updateXfRecordProcess.setRefundTime(new Date());
            updateXfRecordProcess.setIfRefund(ifRefund+1);

            //判断是走什么通道的
            //修改等待表的退款数据
            EntityXfRecordProcess updateXfRecordProces=new EntityXfRecordProcess();
            if ((entityXfRecordProcess.getOpType()==2 || entityXfRecordProcess.getOpTypeDiff()>=200) && canConsMoney > 0){
                //退款金额大于0才能走统一支付
                //查询配置信息向统一平台发起支付
                EntiyXfMerchPayInfo entiyXfMerchPayInfo=payHandleFunService.configure(entityXfRecordProcess);

                if (entiyXfMerchPayInfo ==null){
                    //商户支付渠道未配置"
                    return ResultUtil.error(ResultEnum.Err_3048);
                }
                Map<String,Object> retMap=new HashMap<>();
                retMap.put("company_id",entiyXfMerchPayInfo.getCompanyId());
                retMap.put("user_name",entiyXfMerchPayInfo.getUserName());
                retMap.put("password",entiyXfMerchPayInfo.getPassword());
                retMap.put("out_trade_no",request.getOrigTradeNo());
                if(request.getOrigTradeNo().startsWith("CART")){
                    retMap.put("out_trade_no",entityXfRecordProcess.getPlatOrderNo());
                }
                retMap.put("out_refund_no",request.getTradeNo());
                retMap.put("pos_no",null);
                retMap.put("total_amount", Math.abs(totalAmount));
//                retMap.put("refund_fee", request.getRefundAmount());
                retMap.put("refund_fee",canConsMoney);
                retMap.put("refund_desc", "退款");
                //向统一支付平台发起支付
                String json= "";
//				if(entiyEntiyXfRecordProcess.getPayWay()==28){
//					json= HttpUtils.postsJson(payUrl+"/withholding/refund.do",retMap);
//				}else{
                String payUrl = companyInfoService.getPayCenterUrl(request.getCompanyId(), entiyXfMerchPayInfo.getCompanyId());
                json= HttpUtils.postsJson(payUrl+"/unifiedmicropay/refund.do",retMap);
//				}
                JSONObject results= JSON.parseObject(json);
                if (results.getInteger("code")!=200){
                    log.info("请求方式45:【{}】,机器号:【{}】,入库新增的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecordProcess,"付款码退款失败");
                    log.info("请求方式46:【{}】,机器号:【{}】,统一支付平台的请求参数:【{}】,统一支付平台的返回:【{}】","付款码退款","feeRefund",retMap,json);
                    return ResultUtil.error(ResultEnum.Err_3039);
                }
                Map<String,String> dataMap= (Map<String, String>) JSON.parse(results.getString("data"));
                updateXfRecordProces.setPayChannelNo(entiyXfMerchPayInfo.getCompanyId());

                entityXfRecordProcess.setChannelOrderNo(dataMap.get("refund_id"));
                entityXfRecordProcess.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));

                updateXfRecordProces.setChannelOrderNo(dataMap.get("refund_id"));
                updateXfRecordProces.setPayAmount(-Long.valueOf(dataMap.get("refund_fee")));
            }else if (//entiyEntiyXfRecordProcess.getOpType()==1 &&
                    entityXfRecordProcess.getOpTypeDiff()==100){
                //虚拟账户只允许退一次款，不然对于两个钱包都扣款的交易记录不好退款
//                if(ifRefund>0){
//                    return ResultUtil.error(ResultEnum.Err_3038);
//                }
                if (StringUtils.isNotBlank(entityXfRecordProcess.getCardNo())) {
                    EntityCardInfo entityCardInfo=xfCardInfoService.selectCard(request.getCompanyId(), entityXfRecordProcess.getCardNo());
                    if (entityXfRecordProcess.getOpType()==22 || entityXfRecordProcess.getOpType()==21){
                        entityCardInfo=xfCardInfoService.selectCardByPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                    }

                    if(entityCardInfo!=null){
                        xfCardInfoService.upateCardMoneyA(request.getCompanyId(),entityCardInfo);
                    }
                }

//				EntityXfAccountInfo entityXfAccountInfo=xfAccountInfoService.selectAccount(request.getCompanyId(),entityCardInfo.getAccountNo());
                EntityXfAccountInfo entityXfAccountInfo=xfAccountInfoService.selectAccountPid(request.getCompanyId(), entityXfRecordProcess.getPId());
                Long refundAmount= Long.valueOf(Math.abs(request.getRefundAmount()));
                Long chargeBalance=refundAmount+entityXfAccountInfo.getAccountRechargeMoney();
                //    Long subBalance= Long.valueOf(Math.abs(entityXfRecordProcess.getSubMoney()));
                entityXfRecordProcess.setChargeBalance(chargeBalance);
                entityXfRecordProcess.setPayTime(new Date());
                entityXfRecordProcess.setPayState(1);

                updateXfRecordProces.setId(entityXfRecordProcess.getId());
                updateXfRecordProces.setChargeBalance(chargeBalance);
                updateXfRecordProces.setPayTime(new Date());
                updateXfRecordProces.setPayState(1);

                try {
                    boolean bo = xfAccountInfoService.paraRefundB(request.getCompanyId(),entityXfAccountInfo.getId(),id,entityXfRecordProcess,request.getRefundAmount());
                    if (!bo) {
                        return ResultUtil.error(ResultEnum.Err_3039);
                    }
                }catch (Exception e){
                    StackTraceElement ste =e.getStackTrace()[0];
                    log.info("请求方式148:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund",entityXfRecordProcess,e,ste.getLineNumber());
                    return ResultUtil.error(ResultEnum.Err_3039);
                }

                MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                mqSaveOrderVo.setComId(request.getCompanyId());
                mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

//                Result sveResult=xfRecordFeign.sveXfRecord(entityXfRecordProcess);
//                if (sveResult.getCode()!=200){
//                    log.info("请求方式50:【{}】,机器号:【{}】,入库成功的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecordProcess,"添加入库失败");
//                }

                //修改成功表的原订单表的数据
                updateXfRecordProcess.setComId(request.getCompanyId());
                updateXfRecordProcess.setOrderNo(request.getOrigTradeNo()+entityXfGoodsListProcess.getDishesId());
                updateXfRecordProcess.setMonthValue(monthValue);
//			updateXfRecordProcess.setDeviceNo(request.getMachNo());
                EntityXfRecord entityXfRecord=JSON.parseObject(JSON.toJSONString(updateXfRecordProcess),EntityXfRecord.class);
                Result result=xfRecordFeign.updateXfRecord(entityXfRecord);
                if (result.getCode()!=200){
                    log.info("请求方式49:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecord,"修改原订单信息失败");
                }

                Map<String,Object> map=new HashMap<>();
                map.put("refundAmount",request.getRefundAmount());
                return ResultUtil.success(map);
            }

            try {
                int i=xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(),updateXfRecordProcess);
                if (i<=0){
                    log.info("请求方式47:【{}】,机器号:【{}】,入库修改的数据:【{}】,返回:【{}】","付款码退款","feeRefund",updateXfRecordProcess,"付款码退款失败");
                }
            }catch (Exception e){
                StackTraceElement ste =e.getStackTrace()[0];
                log.info("请求方式48:【{}】,机器号:【{}】,入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund",updateXfRecordProcess,e,ste.getLineNumber());
            }
            if(consState==3 || consState==5 ){
                xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrigOrderNo(),entityXfGoodsListProcess.getDishesId());
            }

            //修改成功表的原订单表的数据
            updateXfRecordProcess.setComId(request.getCompanyId());
            updateXfRecordProcess.setOrderNo(request.getOrigTradeNo());
            updateXfRecordProcess.setMonthValue(monthValue);
//			updateXfRecordProcess.setDeviceNo(request.getMachNo());
            EntityXfRecord entityXfRecord=JSON.parseObject(JSON.toJSONString(updateXfRecordProcess),EntityXfRecord.class);
            Result result=xfRecordFeign.updateXfRecord(entityXfRecord);
            if (result.getCode()!=200){
                log.info("请求方式49:【{}】,机器号:【{}】,修改成功表的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecord,"修改原订单信息失败");
            }
            if(consState==3 || consState==5 ){
                RefundOrderDishesRequest refundOrderDishesRequest =new RefundOrderDishesRequest();
                refundOrderDishesRequest.setComId(entityXfRecordProcess.getComId());
                refundOrderDishesRequest.setOrderNo(request.getOrigTradeNo());
                refundOrderDishesRequest.setGoodsId(Lists.newArrayList(entityXfGoodsListProcess.getDishesId()));
                refundOrderDishesRequest.setMonthValue(entityXfRecordProcess.getMonthValue());
                refundOrderDishesRequest.setRemark("菜品退款");
                xfRecordFeign.refund(refundOrderDishesRequest);
            }

            //新增成功表的退款数据
            Date payTime=new Date();
            entityXfRecordProcess.setPayTime(payTime);
            entityXfRecordProcess.setPayState(1);


//            Result sveResult=xfRecordFeign.sveXfRecord(entityXfRecordProcess);
//            if (sveResult.getCode()!=200){
//                log.info("请求方式50:【{}】,机器号:【{}】,入库成功的数据:【{}】,返回:【{}】","付款码退款","feeRefund", entityXfRecordProcess,"添加入库失败");
//            }

            updateXfRecordProces.setId(entityXfRecordProcess.getId());
            updateXfRecordProces.setPayTime(payTime);
            updateXfRecordProces.setPayState(1);

            try {
                int i=xfRecordProcessService.updateEntityXfRecord(request.getCompanyId(),updateXfRecordProces);
                if (i<=0){
                    log.info("请求方式51:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,返回:【{}】","付款码退款","feeRefund",updateXfRecordProcess,"等待表修改入库失败");
                }
            }catch (Exception e){
                StackTraceElement ste =e.getStackTrace()[0];
                log.info("请求方式52:【{}】,机器号:【{}】,等待表的入库修改的数据:【{}】,异常的返回:【{}】,行号:【{}】","付款码退款","feeRefund",updateXfRecordProcess,e,ste.getLineNumber());
            }

            MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
            mqSaveOrderVo.setComId(request.getCompanyId());
            mqSaveOrderVo.setId(entityXfRecordProcess.getId());
            mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
            saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

            Map<String,Object> map=new HashMap<>();
            map.put("refundAmount",request.getRefundAmount());
            return ResultUtil.success(map);
        }catch (Exception e){
            StackTraceElement ste =e.getStackTrace()[0];
            log.info("请求方式53:【{}】,机器号:【{}】,请求参数:【{}】,异常:【{}】,行号:【{}】","退款异常","feeRefund",request,e,ste.getLineNumber());
            return ResultUtil.error(ResultEnum.Err_3031);
        }
    }

}
